package com.aitemv.services.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jbpm.api.Configuration;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.HistoryService;
import org.jbpm.api.IdentityService;
import org.jbpm.api.ManagementService;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.RepositoryService;
import org.jbpm.api.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aitemv.base.BaseEntity;
import com.aitemv.base.impl.BaseServiceImpl;
import com.aitemv.entity.ProcessEntity;
import com.aitemv.services.ProcessService;
import com.aitemv.services.sqlMap.ProcessSqlMap;

@Service
public class ProcessServiceImpl extends BaseServiceImpl implements
		ProcessService {
	ProcessSqlMap processSqlMap = (ProcessSqlMap) ProcessSqlMap.getInstanceSqlMap();
	 @Autowired
	 protected ProcessEngine processEngine;
	 protected RepositoryService repositoryService;
	 protected ExecutionService executionService;
	 protected ManagementService managementService;
	 protected TaskService taskService;
	 protected HistoryService historyService;
	 protected IdentityService identityService;
	@Override
	public List<? extends BaseEntity> queryForList(ProcessEntity entity) {
		String sql = processSqlMap.conditionSql(entity).toString();
		List<? extends BaseEntity> list = baseDao.getObjList(sql, entity.getClass(), new Object[]{});
		return list;
	}
	 protected ProcessEngine buildProcessEngine() {
		    return Configuration.getProcessEngine();
		  }
	 protected void setUp() throws Exception {
		   // processEngine = buildProcessEngine();

		    repositoryService = processEngine.getRepositoryService();
		    executionService = processEngine.getExecutionService();
		    historyService = processEngine.getHistoryService();
		    managementService = processEngine.getManagementService();
		    taskService = processEngine.getTaskService();
		    identityService = processEngine.getIdentityService();
		  }
	@Override
	public void addOrUpdate(ProcessEntity entity) {
		String sql = processSqlMap.conditionAddOrUpdateSql(entity);
		baseDao.saveOrUpdateObject(sql, entity);
		try {
			setUp();
		} catch (Exception e) {
			e.printStackTrace();
		}
	   String deploymentId = repositoryService.createDeployment()
	        .addResourceFromClasspath("com/aitemv.services/impl/firstJbpm.jpdl.xml")
	        .deploy();
	   System.out.println("流程发布成功--流程ID为："+deploymentId);
	   
	   	Map<String, Object> variables = new HashMap<String, Object>(); 
	    variables.put("value", "测试变量的可以是任何的Object");
	    ProcessInstance processInstance = executionService.startProcessInstanceByKey("firstJbpm", variables);
	    String pid = processInstance.getId();
	    System.out.println("启动第一个流程实例成功----流程实例的id为:"+pid);
	}
}
